<template>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px" class="resource-edit-form">
        <el-form-item label="表单项名称" prop="name">
            <el-input v-if="isEdit" v-model="ruleForm.name" :maxlength="100" placeholder="请输入表单项名称，最多输入100个字符" class="form-input"></el-input>
            <el-input v-else type="textarea" :rows="8" v-model="ruleForm.name" placeholder="请输入表单项名称" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="英文字段" prop="field">
            <el-input v-if="isEdit" v-model="ruleForm.field" :maxlength="100" placeholder="请输入名称对应的英文字段，最多输入100个字符" :disabled="isEdit" class="form-input" @change="checkValueSpace" @input="checkValueSpace" @blur="checkValueSpace"></el-input>
            <el-input v-else type="textarea" :rows="8" v-model="ruleForm.field" placeholder="请输入名称对应的英文字段" :disabled="isEdit" class="form-input" @change="checkValueSpace" @input="checkValueSpace" @blur="checkValueSpace"></el-input>
            <span>不可与其他表单项英文字段重复</span>
        </el-form-item>
        <el-form-item label="配置类型" prop="type">
            <el-select v-model="ruleForm.type" placeholder="请选择配置类型" :disabled="!editOption || isEdit" class="form-input">
                <el-option :label="item.name" :value="item.id" :key="index" v-for="(item, index) in optionsData"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="选项配置" prop="options" v-if="['6', '7'].includes(ruleForm.type)">
            <template v-if="!isEdit">
                <span>每行对应一个选项</span>
                <el-input type="textarea" :disabled="!editOption" v-model="ruleForm.options" :rows="5" class="form-input"></el-input>
            </template>
            <template v-else>
                <div class="options-text" :class="{expand: expand}">
                    <div>已有选项：{{ ruleForm.options.split("\n").join(",").substring(0, ruleForm.options.split("\n").join(",").length - 1) }}</div>
                    <span class="btn" @click="expand = !expand">展开全部<i :class="expand ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
                </div>
                <el-input type="textarea" v-model="ruleForm.newOptions" :rows="5" class="form-input"></el-input>
            </template>
        </el-form-item>
<!--        <el-form-item label="单位" prop="unit">-->
<!--            <el-select v-model="ruleForm.unit" clearable placeholder="请选择单位" class="form-input">-->
<!--                <el-option :label="item.name" :value="item.id" :key="index" v-for="(item, index) in unitsData"></el-option>-->
<!--            </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="检索展示" prop="isSearchShow">
            <el-switch
                v-model="ruleForm.isSearchShow"
                active-color="#32A78F"
                inactive-color="#CACDCE">
            </el-switch>
        </el-form-item>
        <el-form-item label="单选多选展示状态" prop="isDownShow">
            <el-switch
                v-model="ruleForm.isDownShow"
                active-color="#32A78F"
                inactive-color="#CACDCE">
            </el-switch>
        </el-form-item>
        <el-form-item label="分类" prop="label">
            <el-cascader
                class="form-input"
                v-model="ruleForm.label"
                :options="labelsData"
                :props="defaultProps">
            </el-cascader>
        </el-form-item>
        <slot></slot>
    </el-form>
</template>

<script lang="ts">
import Vue from "vue";
import { Component, Prop } from "vue-property-decorator";
import { State } from 'vuex-class';
import { dialogSelect } from "../select-department/index";

interface FormModel{
    id: number;
    name: string;
    type: string;
    options: string;
    department: number[];
    label: string[];
    isSearchShow: boolean;
    isDownShow: boolean;
}

const checkLevel = (rule: any, value: any, callback: any) => {
    if (value.length && value.length !== 3) {
        callback(new Error('只能选择三级分类'));
    } else {
        callback();
    }
};

@Component({
    name: "AddOptionNotAlive"
})
export default class AddOptionNotAlive extends Vue {
    @State(state => state.user.userInfo) user: any;
    @Prop({ default: "" }) private id: any;
    @Prop({ default: () => { return {}; } }) private fillData!: any;
    @Prop({ default: true }) private editOption!: boolean;
    @Prop({ default: false }) private isEdit!: boolean;

    // 级联选中内容
    value: any = "";
    ruleForm: any = {
        id: '',
        name: '',
        type: '',
        options: "",
        label: [],
        isSearchShow: true,
        isDownShow: true,
        newOptions: ""
    }

    optionsData = []
    unitsData = []
    labelsData = []
    selectedDepartment = []
    defaultProps = {
        value: "id",
        label: "name"
    }

    expand = false

    rules = {
        name: [
            { required: true, message: '请输入表单项名称', trigger: 'blur' }
        ],
        field: [
            { required: true, message: '请输入名称对应的英文字段', trigger: 'blur' }
        ],
        type: [
            { required: true, message: '请选择配置类型', trigger: 'change' }
        ],
        label: [
            { required: true, message: '请选择分类', trigger: 'change' },
            { validator: checkLevel, trigger: 'change' }
        ],
        options: [
            { required: true, message: "请添加选项配置" }
        ]
    }

    created() {
        if (this.id) this.initData();
        this.getOptions();
        this.getUnits();
        this.getLabels();
        this.initFillData();
    }

    checkValueSpace() {
        this.ruleForm.field = this.ruleForm.field.replace(/\s/g, "");
        this.ruleForm.field = this.ruleForm.field.replace(/[`~!@#$%^&*()\-+=/\\|{[\]};':",.<>?，。、？；‘’“”【】｛｝！￥%…（）——]/g, "");
    }

    // 初始化回显数据
    initFillData() {
        if (JSON.stringify(this.fillData) !== "{}") {
            this.ruleForm = {
                id: '',
                name: this.fillData.name || "",
                type: this.fillData.valueKindId ? this.fillData.valueKindId.toString() : "1",
                options: this.fillData.optionList ? this.fillData.optionList.map((cur: any) => cur.name).join(`\n`) + `\n` : "",
                label: [],
                isSearchShow: this.fillData.isSearchShow || true,
                isDownShow: this.fillData.isDownShow || true,
                newOptions: ""
            };
        }
    }

    // 初始化表单
    async initData() {
        const res = await this.$server["resource/getRowData"]({
            data: {
                id: this.$route.query.id
            }
        });
        if (res.data.code === 200) {
            const { id, name, field, valueKindId, options, labelIds, isSearchShow, isDownShow } = res.data.data;
            this.ruleForm = {
                id: id,
                name: name,
                field: field,
                type: valueKindId || "1",
                options: options && options.length ? options.map((cur: any) => cur.name).join(`\n`) + `\n` : "",
                label: this.ruleForm.label || labelIds,
                isSearchShow: isSearchShow === 0,
                isDownShow: isDownShow === 0,
                newOptions: ""
            };
        } else {
            this.$message.error(res.data.message || "接口请求错误!");
        }
    }

    // 选择所属部门
    chooseDepartment() {
        dialogSelect({
            selectedList: this.selectedDepartment,
            sure: (vm: any, model: any) => {
                vm.close();
                this.selectedDepartment = model.selectedList;
            }
        });
    }

    // 获取分类
    async getLabels() {
        const res = await this.$server["business/config/tree"]({
            data: {}
        });
        if (res.data.code === 200) {
            if (res.data.data && res.data.data[0].children) {
                this.ruleForm.label = this.getLabel(res.data.data[0].children).length === 3 ? this.getLabel(res.data.data[0].children) : [];
                this.labelsData = this.getTypeList(res.data.data[0].children);
                if (this.isEdit) {
                    this.labelsData = this.labelsData.filter((item: any) => item.id === this.ruleForm.label[0]);
                    this.labelsData.forEach((item: any) => {
                        item.children = item.children.filter((it: any) => it.id === this.ruleForm.label[1]);
                    });
                }
            } else {
                this.labelsData = [];
            }
        } else {
            this.$message.error(res.data.message || "接口请求错误!");
        }
    }

    // 获取默认分类
    getLabel(arr: any) {
        let ids: any[] = [];
        for (let i = 0; i < arr.length; i++) {
            if (this.$route.query.typeId === arr[i].id) {
                ids.unshift(arr[i].id);
                return ids;
            }
            if (arr[i].children && arr[i].children.length) {
                if (this.getLabel(arr[i].children).length) {
                    ids = this.getLabel(arr[i].children);
                    ids.unshift(arr[i].id);
                }
            }
        }
        return ids;
    }

    // 分类选项处理
    getTypeList(arr: any) {
        arr.forEach((item: any) => {
            if (item.children && item.children.length) {
                item.children = this.getTypeList(item.children);
            } else {
                item.children = null;
            }
        });
        return arr;
    }


    // 获取配置类型
    async getUnits() {
        const res = await this.$server.getUnits({
            data: {}
        });
        if (res.data.code === 200) {
            this.unitsData = res.data.data;
        } else {
            this.$message.error(res.data.message || "接口请求错误!");
        }
    }

    // 获取配置类型
    async getOptions() {
        const res = await this.$server.getOptions({
            data: {}
        });
        if (res.data.code === 200) {
            this.optionsData = res.data.data;
        } else {
            this.$message.error(res.data.message || "接口请求错误!");
        }
    }

    // 提交表单
    submitForm(c: any) {
        (this.$refs.ruleForm as any).validate(async(valid: any) => {
            if (valid) {
                this.ruleForm.field = this.ruleForm.field.replace(/\s/g, "");
                this.ruleForm.field = this.ruleForm.field.replace(/[`~!@#$%^&*()\-+=/\\|{[\]};':",.<>?，。、？；‘’“”【】｛｝！￥%…（）——]/g, "");
                this.$emit("sure", this.ruleForm);
                c(this.ruleForm);
            } else {
                c("");
            }
        });
    }

    async deleteRow(row: any, index: number) {
        if (!row.id) {
            this.ruleForm.options.splice(index, 1);
            return false;
        }
        const res = await this.$server["resource/checkDeleteOptions"]({
            params: {
                id: row.id
            },
            data: {
                id: row.id
            },
            loader: false
        });
        if (res.data.code === 200) {
            if (res.data.data) {
                this.$confirm('是否确认删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.ruleForm.options.splice(index, 1);
                }).catch();
            } else {
                this.$message.error("该选项已有用户选择，不允许删除");
            }
        } else {
            this.$message.error(res.data.message || "接口请求错误!");
        }
    }

    addOptions() {
        this.ruleForm.options.unshift({
            // sort: this.ruleForm.options.length ? Number(this.ruleForm.options[0].sort) + 1 : "0",
            name: ""
        });
    }

    // 修改排序值
    inputBlur() {
        function compare(property: any) {
            return function(a: any, b: any) {
                const value1 = a[property];
                const value2 = b[property];
                return -(Number(value1) - Number(value2));
            };
        }
        this.ruleForm.options = this.ruleForm.options.sort(compare('sort'));
    }

    goBack() {
        this.$router.go(-1);
    }
}
</script>

<style scoped lang="scss">
    .resource-edit-form {
        width: 5rem;
        .form-input {
            width: 3.8rem;
        }
    }
    .ask-city-cascader-box {
        width: 380px;
        margin-bottom: 10px;
    }

    .options-text {
        @include flexLayout(flex,justify,normal);
        div {
            width: calc(100% - 80px);
            @include textEllipsis();
        }
        .btn {
            color: #2C82C9;
            cursor: pointer;
        }
        &.expand {
            div {
                @include flexLayout(flex,normal,normal);
                overflow: unset;
                white-space: unset;
                padding-top: 7px;
                line-height: 22px;
                word-break: break-all;
            }
        }
    }
</style>
